package com.whh.permission.service.serviceImpl;

import com.whh.permission.dao.IRoleDao;
import com.whh.permission.po.Node;
import com.whh.permission.po.Role;
import com.whh.permission.po.RoleMenu;
import com.whh.permission.service.IRoleService;
import com.whh.permission.util.TreeBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private TreeBuilder treeBuilder;
    @Resource
    private IRoleDao iRoleDao;

    @Override
    public List<Role> queryRoleAll() {
        return iRoleDao.queryRoleAll();
    }

    @Override
    public Role queryRoleById(Integer id) {
        return iRoleDao.queryRoleById(id);
    }

    @Override
    public void addRole(Role role) {
        iRoleDao.addRole(role);
    }

    @Override
    public void updateRole(Role role) {
        iRoleDao.updateRole(role);
    }

    @Override
    public void deleteRoleById(Integer id) {
        iRoleDao.deleteRoleById(id);
    }

    @Override
    public void deleteRoleMenuByRoleId(Integer roleId) {
        iRoleDao.deleteRoleMenuByRoleId(roleId);
    }

    @Override
    @Transactional
    public void insertForEach(int[] ids,int roleId) {
        //先删除原来的映射关系
        this.deleteRoleMenuByRoleId(roleId);
        //遍历添加
        List<RoleMenu> list = new ArrayList<>();
        for (int menuId:ids){
            list.add(new RoleMenu(roleId,menuId));
        }
        iRoleDao.insertForEach(list);
    }

    @Override
    public List<Node> queryRoleTree() {
        List<Node> list = iRoleDao.queryDeptTree();
        treeBuilder.buildTree(list);
        return list;
    }
}
